package yunquan.wang.base.spring.security;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import yunquan.wang.base.service.impl.ServiceLog;
import yunquan.wang.modules.base.entity.Rolesinfo;
import yunquan.wang.modules.base.entity.UserBasic;
import yunquan.wang.modules.base.service.UserBasicService;

@Service("userDetailService")
@Transactional(value = "jpaTransaction")
public class UserDetailService implements UserDetailsService {
	@Resource
	private UserBasicService userBasicService;
	@Resource
	private SecurityService securityService;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		UserBasic user = userBasicService.findByLoginName(username);
	
		if (user == null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);
		UserDetail userdetail =new UserDetail(
				user.getLoginName(), user.getPassword(), enabled,
				accountNonExpired, credentialsNonExpired, accountNonLocked,
				grantedAuths);
		userdetail.setUserId(user.getId());
		ServiceLog.log(this.getClass(), username, "用户登录", "");
//	/	userdetail.setGroupId(user.getGroupInfo().getId());
		return userdetail;
	}

	private Set<GrantedAuthority> obtainGrantedAuthorities(UserBasic user) {
		Set<GrantedAuthority> gaSet = new HashSet<GrantedAuthority>();
		for (Rolesinfo ri : user.getRolesinfos()) {
			Set<GrantedAuthority> raList = securityService.getRoleAuthority(ri
					.getId());
			gaSet.addAll(raList);
		}
		return gaSet;
	}

}

/**
 * Copyright (c) 2009,天安怡和 All rights reserved.
 */
